package com.link.play.fit.ai.utils

import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import android.view.ViewGroup
import com.link.play.fit.ai.utils.ScreenUtil.Companion.getScreenHeight
import com.link.play.fit.ai.utils.ScreenUtil.Companion.getScreenWidth
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


object BitmapUtils {

    // 获取屏幕截图 Bitmap
    fun getScreenBitmap(view: View): Bitmap {
        val bitmap = Bitmap.createBitmap(
            view.width,
            view.height,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }


    // 保存为文件（兼容 Android 11+）
    fun saveBitmapToFile(bitmap: Bitmap, context: Context): File? {
        return try {
            val fileName = "screenshot_${System.currentTimeMillis()}.png"

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10+ 使用 MediaStore
                val contentValues = ContentValues().apply {
                    put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                    put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
                    put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
                }

                val uri = context.contentResolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    contentValues
                )

                uri?.let {
                    context.contentResolver.openOutputStream(it).use { outputStream ->
                        outputStream?.let { it1 ->
                            bitmap.compress(
                                Bitmap.CompressFormat.PNG, 100,
                                it1
                            )
                        }
                    }
                    File(uri.path ?: "") // 转换为 File 对象（注意：实际访问需用 ContentResolver）
                }
            } else {
                // Android 9 及以下使用传统文件路径
                val storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                val file = File(storageDir, fileName)
                FileOutputStream(file).use { out ->
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
                }
                file
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    fun saveBitmapToUri(bitmap: Bitmap, context: Context): Uri? {
        val fileName = "kcal_${System.currentTimeMillis()}.png"

        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
            put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
            put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
        }

        val uri = context.contentResolver.insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            contentValues
        )

        uri?.let {
            context.contentResolver.openOutputStream(it).use { outputStream ->
                outputStream?.let { it1 ->
                    bitmap.compress(
                        Bitmap.CompressFormat.PNG, 100,
                        it1
                    )
                }
            }

        }

        return uri
    }

    fun captureScreen(activity: Activity): Bitmap? {
        val decorView = activity.window.decorView
        decorView.isDrawingCacheEnabled = true
        decorView.buildDrawingCache()
        val bitmap = decorView.drawingCache?.copy(Bitmap.Config.ARGB_8888, false)
        decorView.isDrawingCacheEnabled = false // 及时释放缓存‌:ml-citation{ref="1,4" data="citationList"}
        return bitmap
    }

    fun getScreenBitmap2(view: View): Bitmap {
        val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        view.draw(canvas)
        return bitmap
    }

    /**
     * 获取当前屏幕截图，不包含状态栏
     *
     * @param activity activity
     * @return Bitmap
     */
    fun captureWithStatusBar(activity: Activity): Bitmap? {
        val view = activity.window.decorView
        view.isDrawingCacheEnabled = true
        view.buildDrawingCache()
        val bmp = view.drawingCache
        val width: Int = getScreenWidth()
        val height: Int = getScreenHeight()
        val ret = Bitmap.createBitmap(bmp, 0, 0, width, height)
        view.destroyDrawingCache()
        return ret
    }

    fun saveBitmap(context: Context, bitmap: Bitmap, fileName: String): String? {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            saveBitmapAndroid10AndAbove(context, bitmap, fileName)
        } else {
            saveBitmapBelowAndroid10(context, bitmap, fileName)
        }
    }

    private fun saveBitmapAndroid10AndAbove(
        context: Context,
        bitmap: Bitmap,
        fileName: String
    ): String? {
        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
            put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
            put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
        }

        val resolver = context.contentResolver
        val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

        return try {
            uri?.let {
                val outputStream: OutputStream = resolver.openOutputStream(it)!!
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
                outputStream.close()
                it.toString()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    private fun saveBitmapBelowAndroid10(
        context: Context,
        bitmap: Bitmap,
        fileName: String
    ): String? {
        val directory =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        if (!directory.exists()) {
            directory.mkdirs()
        }
        val file = File(directory, fileName)
        return try {
            val outputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
            outputStream.flush()
            outputStream.close()
            file.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

}